import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 最大级别的规则，对应的组件，会显示在App.vue中
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/reg', component: () => import('@/views/Reg.vue') },
  // 后台首页
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    // 嵌套组件
    children: [
      { path: '/home', component: () => import('@/views/Chart.vue') },
      { path: '/user-info', component: () => import('@/views/user/UserInfo.vue') },
      { path: '/user-pwd', component: () => import('@/views/user/RePwd.vue') },
      { path: '/user-avatar', component: () => import('@/views/user/UserAvatar.vue') },
      { path: '/art-cate', component: () => import('@/views/article/CateList.vue') },
      { path: 'art-list', component: () => import('@/views/article/ArtList.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 这里添加导航守卫
router.beforeEach((to, from, next) => {
  // to.path 表示即将要访问的路由地址
  // next() 表示放行, 直接通过   next(false) 不放心, 也不跳转, 原地不动   next('/login) 跳转到登录
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    // 说明访问的不是登录,也不是注册, 那就得判断有没有token
    if (store.state.user.token) {
      next() // 本地存储有token, 则放行
    } else {
      next('/login')
    }
  }
})

export default router
